﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.ComponentModel.Composition;
using Microsoft.Practices.ServiceLocation;

namespace Dynamic_UI_Framework
{
    public class Element : IElement
    {
        public FrameworkElement Target
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public IVisual Owner
        {
            get;
            set;
        }

        public void Activate(IVisual v)
        {
            if (Owner != null)
                Owner.Activate(this);

        }

        public List<System.Windows.Controls.MenuItem> GetMenuItem()
        {
            return new List<System.Windows.Controls.MenuItem>();
        }
    }

    [Export("Element", typeof(IBuilder))]
    public class ElementBuilder : IBuilder
    {
        public UINode GetUINode(IVisual obj)
        {
            Element ele = obj as Element;
            if (ele == null)
                return null;

            UINode node = new UINode();
            node.Target = ele;
            node.Name = ele.Name;
            node.TypeName = ele.GetType().Name;
            node.Properties.Add("target", ele.Target.GetType().Name);
            return node;
        }
        public IVisual Build(UINode node)
        {
            if (node.Properties.ContainsKey("target") == false)
                throw new Exception();

            string contaceName = node.Properties["target"].ToString();
            IElement element = ServiceLocator.Current.GetInstance<IElement>(contaceName);
            (element as FrameworkElement).Width = 100;
            (element as FrameworkElement).Height = 100;

            ElementAdapterMapping mapping = ServiceLocator.Current.GetInstance<ElementAdapterMapping>();
            IAdapter adapter = mapping.GetMapping(contaceName);
            if (adapter == null)
                throw new Exception("adapter == null");

            IVisual v = adapter.Initialize(element, node.Name);
            return v;
        }
    }
}
